package com.lzp.badminton.util.loginUtil;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lzp.badminton.config.ResultMessage;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
 
public class UserInterceptor implements HandlerInterceptor {
 
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Autowired
	private ResultMessage resultMessage;
 
	/**
	 * 在请求处理之前进行调用（Controller方法调用之前）
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) {
 
		// 检查用户传递的 token是否合法
		TokenInfo tokenInfo = this.getUserToKen(request);
		if (StringUtils.isBlank(tokenInfo.getUserId()) && StringUtils.isBlank(tokenInfo.getToken())) {
			// 返回登录
			returnErrorResponse(response);
			return false;
		}
		try {
			String token = redisTemplate.opsForValue().get(tokenInfo.getUserId());
			if (token != null && token.equals(tokenInfo.getToken())) {
				System.out.println("校验成功");
				return true;
			} else {
				System.out.println("校验失败，返回登录");
				returnErrorResponse(response);
				return false;
			}
		} catch (Exception e) {
			System.out.println("校验失败,信息匹配错误，返回登录");
			returnErrorResponse(response);
			return false;
		}
 
	}
 
	/**
	 * 在cookie中获取用户传递的token
	 */
	private TokenInfo getUserToKen(HttpServletRequest request) {
		TokenInfo info = new TokenInfo();
		String userId = request.getHeader("userId");
		String token = request.getHeader("token");
		if (StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(token)) {
			info.setUserId(userId);
			info.setToken(token);
		}
		return info;
	}
 
	/**
	 * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView mv)
			throws Exception {
 
	}
 
	/**
	 * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行 （主要是用于进行资源清理工作）
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception ex)
			throws Exception {
 
	}
 
	public void returnErrorResponse(HttpServletResponse response){
		OutputStream out = null;
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json; charset=utf-8");
			// 返回用户未登录的信息
			resultMessage.fail("401", "校验失败, 用户未登录");
			response.getWriter().print(JSONObject.fromObject(resultMessage));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
 
}